<template>
	<view class="login-container">
		<view class="logo-area">
			<image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
			<text class="app-name">糖护卫</text>
			<text class="app-slogan">您的贴心血糖管理助手</text>
		</view>
		
		<view class="login-form">
			<view class="welcome-text">欢迎使用糖护卫</view>
			<view class="sub-title">登录后即可使用完整功能</view>
			
			<view class="login-btn-area">
				<!-- 第一步：选择微信登录 -->
				<button v-if="step === 1" class="wx-login-btn" @tap="startWxLogin">
					<image class="wx-icon" src="/static/images/wechat.png" mode="aspectFit"></image>
					<text>微信一键登录</text>
				</button>
				
				<!-- 第二步：完善用户信息 -->
				<view v-if="step === 2" class="profile-area">
					<view class="avatar-section">
						<text class="section-title">点击更换头像</text>
						<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
							<image class="avatar" :src="userInfo.avatarUrl || '/static/images/avatar.png'" mode="aspectFill"></image>
						</button>
					</view>
					
					<view class="nickname-section">
						<text class="section-title">请输入昵称</text>
						<input
							type="nickname"
							class="nickname-input"
							placeholder="请输入昵称"
							placeholder-style="color: #999"
							v-model="userInfo.nickName"
							@change="onNicknameChange"
						/>
					</view>
					
					<button class="confirm-btn" @tap="handleWxLogin" :disabled="!userInfo.avatarUrl || !userInfo.nickName">完成</button>
					<button class="cancel-btn" @tap="resetSteps">返回</button>
				</view>
				
				<view class="privacy-policy">
					<text>登录即表示您已同意</text>
					<text class="link" @tap="goToPrivacy">《用户协议和隐私政策》</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { wxLogin } from '../../common/api/user.js'
	import config from '../../common/config.js'
	
	export default {
		data() {
			return {
				loading: false,
				step: 1, // 步骤：1=选择登录方式，2=完善用户信息
				userInfo: {
					nickName: '',
					avatarUrl: '',
					gender: 0,
					country: '',
					province: '',
					city: '',
					language: ''
				},
				// 添加配置
				config: config
			}
		},
		onLoad() {
			// 检查是否已登录
			const token = uni.getStorageSync('xuetang_token')
			if (token) {
				this.navigateToHome()
				return
			}
			
			// 检查是否已获取用户信息
			const savedUserProfile = uni.getStorageSync('userProfile')
			if (savedUserProfile) {
				this.userInfo = {
					nickName: savedUserProfile.nickName || '',
					avatarUrl: savedUserProfile.avatarUrl || '',
					gender: savedUserProfile.gender !== undefined ? savedUserProfile.gender : 0,
					country: savedUserProfile.country || '',
					province: savedUserProfile.province || '',
					city: savedUserProfile.city || '',
					language: savedUserProfile.language || ''
				}
				console.log('从本地存储获取到用户信息:', this.userInfo)
			}
		},
		methods: {
			// 第一步：点击微信登录按钮，获取登录凭证
			startWxLogin() {
				uni.showLoading({
					title: '登录中...',
					mask: true
				})
				
				// 获取微信登录凭证
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						if (loginRes.code) {
							// 保存登录凭证
							this.loginCode = loginRes.code
							console.log('获取到微信登录凭证:', loginRes.code)
							
							// 登录凭证获取成功后，进入第二步获取用户信息
							uni.hideLoading()
							this.step = 2
						} else {
							uni.hideLoading()
							uni.showToast({
								title: '微信登录失败，请重试',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('微信登录失败:', err)
						uni.hideLoading()
						uni.showToast({
							title: '微信登录失败，请重试',
							icon: 'none'
						})
					}
				})
			},
			
			// 选择头像
			onChooseAvatar(e) {
				const avatarUrl = e.detail.avatarUrl
				console.log('选择的头像:', avatarUrl)
				
				// 更新头像
				this.userInfo.avatarUrl = avatarUrl
				
				// 更新本地存储
				this.updateLocalUserProfile()
			},
			
			// 昵称变化
			onNicknameChange(e) {
				console.log('输入的昵称:', e.detail.value)
				this.userInfo.nickName = e.detail.value
				
				// 更新本地存储
				this.updateLocalUserProfile()
			},
			
			// 更新本地用户信息
			updateLocalUserProfile() {
				uni.setStorageSync('userProfile', this.userInfo)
				console.log('更新本地用户信息:', this.userInfo)
			},
			
			// 处理微信登录
			async handleWxLogin() {
				if (this.loading) return
				
				// 验证用户信息
				if (!this.userInfo.avatarUrl) {
					uni.showToast({
						title: '请选择头像',
						icon: 'none'
					})
					return
				}
				
				if (!this.userInfo.nickName) {
					uni.showToast({
						title: '请输入昵称',
						icon: 'none'
					})
					return
				}
				
				this.loading = true
				
				// 确保先存储用户信息
				this.updateLocalUserProfile()
				
				uni.showLoading({
					title: '登录中...',
					mask: true
				})
				
				try {
					// 检查是否有登录凭证
					if (!this.loginCode) {
						// 如果没有登录凭证，重新获取
						uni.hideLoading()
						uni.showToast({
							title: '登录凭证已过期，请重试',
							icon: 'none'
						})
						this.step = 1
						this.loading = false
						return
					}
					
					// 获取API基础URL - 使用组件内导入的配置
					const apiBaseUrl = this.config.apiBaseUrl || 'http://localhost:8080'
					console.log('使用API基础URL:', apiBaseUrl)
				
					// 直接调用后端登录接口
					uni.request({
						url: `${apiBaseUrl}/user/login`,
						method: 'POST',
						data: {
							code: this.loginCode,
							userInfo: this.userInfo
						},
						success: (res) => {
							uni.hideLoading()
							this.loading = false
							
							if (res.statusCode === 200 && res.data.code === 0) {
								// 保存登录信息
								uni.setStorageSync('xuetang_token', res.data.data.token)
								uni.setStorageSync('xuetang_user_info', res.data.data.userInfo)
								
								uni.showToast({
									title: '登录成功',
									icon: 'success'
								})
								
								// 登录成功后跳转到首页
								setTimeout(() => {
									this.navigateToHome()
								}, 1500)
							} else {
								// 登录失败
								uni.showToast({
									title: res.data.message || '登录失败，请重试',
									icon: 'none'
								})
							}
						},
						fail: (err) => {
							console.error('登录请求失败:', err)
							uni.hideLoading()
							this.loading = false
							
							uni.showToast({
								title: '网络请求失败，请检查网络设置',
								icon: 'none'
							})
						}
					})
				} catch (error) {
					console.error('登录错误:', error)
					this.loading = false
					uni.hideLoading()
					
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					})
				}
			},
			
			// 重置步骤
			resetSteps() {
				this.step = 1
			},
			
			// 跳转到首页
			navigateToHome() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			
			// 跳转到隐私政策页面
			goToPrivacy() {
				uni.navigateTo({
					url: '/pages/privacy/index'
				})
			}
		}
	}
</script>

<style lang="scss">
.login-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	display: flex;
	flex-direction: column;
	padding: 60rpx 40rpx;
	
	.logo-area {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 80rpx;
		margin-bottom: 100rpx;
		
		.logo {
			width: 180rpx;
			height: 180rpx;
			margin-bottom: 30rpx;
		}
		
		.app-name {
			font-size: 48rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 10rpx;
		}
		
		.app-slogan {
			font-size: 28rpx;
			color: #666;
		}
	}
	
	.login-form {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 50rpx 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
		
		.welcome-text {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			text-align: center;
			margin-bottom: 10rpx;
		}
		
		.sub-title {
			font-size: 28rpx;
			color: #666;
			text-align: center;
			margin-bottom: 60rpx;
		}
		
		.login-btn-area {
			.wx-login-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: #07c160;
				color: #fff;
				font-size: 32rpx;
				height: 90rpx;
				border-radius: 45rpx;
				margin-bottom: 30rpx;
				
				.wx-icon {
					width: 40rpx;
					height: 40rpx;
					margin-right: 10rpx;
				}
			}
			
			.profile-area {
				display: flex;
				flex-direction: column;
				align-items: center;
				margin-bottom: 30rpx;
				
				.section-title {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 20rpx;
					text-align: center;
					display: block;
				}
				
				.avatar-section {
					margin-bottom: 40rpx;
					width: 100%;
					display: flex;
					flex-direction: column;
					align-items: center;
				}
				
				.avatar-wrapper {
					background: none;
					border: none;
					padding: 0;
					width: 150rpx;
					height: 150rpx;
					border-radius: 50%;
					overflow: hidden;
					
					&::after {
						border: none;
					}
				}
				
				.avatar {
					width: 150rpx;
					height: 150rpx;
					border-radius: 50%;
				}
				
				.nickname-section {
					width: 100%;
					margin-bottom: 40rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
				}
				
				.nickname-input {
					width: 100%;
					height: 80rpx;
					background-color: #f5f5f5;
					border-radius: 40rpx;
					padding: 0 30rpx;
					font-size: 28rpx;
					color: #333;
				}
				
				.confirm-btn {
					width: 100%;
					background-color: #07c160;
					color: #fff;
					font-size: 32rpx;
					height: 90rpx;
					line-height: 90rpx;
					border-radius: 45rpx;
					margin-bottom: 20rpx;
				}
				
				.cancel-btn {
					width: 100%;
					background-color: #f5f5f5;
					color: #666;
					font-size: 32rpx;
					height: 90rpx;
					line-height: 90rpx;
					border-radius: 45rpx;
				}
			}
			
			.privacy-policy {
				font-size: 24rpx;
				color: #999;
				text-align: center;
				
				.link {
					color: #8cc9a1;
				}
			}
		}
	}
}
</style> 